#!/usr/bin/env python
# -*- coding: utf8 -*-
#-------------------------------------------------------------------------------
# Name:        pyvideo
# Purpose:      下载pyvideo的视频
#
# Author:      iori
#
# Created:     04-05-2014
# Copyright:   (c) iori 2014
# Licence:     GPLv3
#-------------------------------------------------------------------------------
import urllib
import argparse
import sys

import requests
from pyquery import PyQuery

def download(url):
    dom = PyQuery(url=url)
    tids = set()
    links = []
    prefix = '/video/'
    def filter_link(i, v):
        href = PyQuery(v).attr('href')
        if not href:
            return
        if href.startswith(prefix):
            pos = href.find('/', len(prefix))
            tids.add(href[len(prefix):pos])
    dom('a').each(filter_link)
    rest_api = 'http://www.pyvideo.org/api/v2/video/{}?format=json'.format
    for tid in tids:
        meta = requests.get(rest_api(tid)).json()
        if meta.get('source_url'):
            links.append(meta.get('source_url'))
    return links
    pass


def main():

    with open('video_url.txt', 'w') as fp:
        for url in sys.argv[1:]:
            links = download(url)
            fp.write('\n'.join(links))

if __name__ == '__main__':
    main()
